package com.msmall.community.common.service.impl;

import java.util.List;

import com.msmall.base.cache.CacheFactory;
import com.msmall.base.exception.DataNotFoundException;
import com.msmall.base.pager.MatchType;
import com.msmall.base.service.impl.BaseManagerImpl;
import com.msmall.base.util.ConstantDB;
import com.msmall.base.util.Constants;
import com.msmall.community.common.CommunityInitialize;
import com.msmall.community.common.dao.RankRuleDao;
import com.msmall.community.common.model.RankRule;
import com.msmall.community.common.service.RankRuleManager;
import com.msmall.community.user.model.UserInfo;

public class RankRuleManagerImpl extends BaseManagerImpl<RankRule, Long> implements RankRuleManager{

	private RankRuleDao rankRuleDao;

	public void setRankRuleDao(RankRuleDao rankRuleDao) {
		this.rankRuleDao = rankRuleDao;
	}

	public RankRule getRankRule(int level) throws Exception{
		RankRule rankRule = (RankRule) CacheFactory.getInstance().getCache(Constants.CACHE_NAME_RANKRULE).get(level);
		if(rankRule == null){
			rankRule = loadRankRule(level);
		}
		return rankRule;
	}
	
	public RankRule loadRankRule(int level) throws Exception {
		try{
			List list = rankRuleDao.getByProperty(RankRule.class, "levels", MatchType.EQ, String.valueOf(level));
			if(null != list && list.size() > 0){
				RankRule rule = (RankRule) list.get(0);
				CacheFactory.getInstance().getCache(Constants.CACHE_NAME_RANKRULE).put(level, rule);
				return rule;
			}
			throw new DataNotFoundException("RankRule not found with level :" + level);
		} catch(Exception e){
			throw e;
		}
	}
	
	public void saveRankRule(RankRule rankRule){
		rankRuleDao.save(rankRule);
		CommunityInitialize.refreshRankRule();
	}

	public boolean promotion(UserInfo userInfo) {
		return promotion(userInfo.getLevels(), userInfo.getScore().getScore());
	}

	public boolean promotion(int levels, Long score) {
		try {
			int nextLevels = levels + 1;
			RankRule next = getRankRule(nextLevels);
			if(ConstantDB.AVALIABLE.compareTo(next.getEnabled()) == 0){
				Long nextScore = next.getScore();
				if(score >= nextScore){
					return true;
				}else{
					return false;
				}
			}else{
				return promotion(levels++, score);
			}
		} catch (Exception e) {
			return false;
		}
	}
}
